<?php

class DBIntegrity
{
	private $_dirFiles;
	private $_dbFiles;
	private $_db;
	private $_media;
	public $_newFiles;
	
	public function __construct($media)
	{
	    $this->_db = new PDO('mysql:host=localhost;port=3306;dbname=mediadevil', 'root', 'c3589');
	    $this->_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	    
    	$this->setMedia($media);
		if($this->getDirFiles() && $this->getDbFiles())
		{
			$this->compareFiles($this->_dirFiles, $this->_dbFiles);
			return true;
		}
		else return false;
	}
	
	public function setMedia($media)
	{
		$array = array('audio','video','books','software','photos');
		if(in_array($media, $array))
		{
			$this->_media = $media;
			return true;
		}
		else return false;
	}
	
	public function getDirFiles()
	{
	    $olddir = getcwd();
        chdir('media/'.$this->_media.'/');
        
        $dh = dir(getcwd());
        while (false !== ($file = $dh->read()))
        {
        	if($file != '.' && $file != '..')
        	{
        		$filepath = getcwd().$file;
				$fileinfo = pathinfo($filepath);
				$md5sum = md5_file($filepath);
        		$this->_dirFiles[] = array('file_name' => $fileinfo['filename'], 'file_type' => $this->_media, 'file_md5' => $md5sum, 'file_extension' => $fileinfo['extension']);
        	}
        }
        $dh->close();
        chdir($olddir);	
        return true;
	}
	
	public function getDbFiles()
	{
		$sql = 'SELECT file_name,file_type,file_md5,file_extension FROM media_files WHERE file_type=\''.$this->_media.'\'';
    	if(!$query = $this->_db->query($sql)) return false;
    	
    	while($result = $query->fetch(PDO::FETCH_ASSOC))
    	{
    	    $this->_dbFiles[] = $result;
    	}
    	
		return true;
	}
	
	public function compareFiles($dirFiles, $dbFiles)
	{
			$diff = array_diff($dirFiles, $dbFiles);
			var_dump($diff);
		
		
	}
}